//
//  IJTextAndPicsCell.m
//  iwjw
//
//  Created by ChenJianjun on 2016/12/14.
//  Copyright © 2016年 iwujwu. All rights reserved.
//

#import "IJTextAndPicsCell.h"
#import "IJTextView.h"
#import "IJIssuePicCell.h"
#import "IJIssueAddPicCell.h"
#import "JCCollectionViewGridLayout.h"
#import "IJImagesPicker.h"

static NSInteger const kIJMaxImagesCount = 9;

@interface IJTextAndPicsCell ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) IJTextView *textView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) IJImagesPicker *imagesPicker;

@property (nonatomic, strong) NSString *issueText;
@property (nonatomic, strong) NSMutableArray *picList;

@end

@implementation IJTextAndPicsCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    [self setupSubviews];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self setupSubviews];
    }
    return self;
}

- (NSString *)issueText
{
    _issueText = self.textView.text;
    return _issueText;
}

- (CGFloat)cellHeight
{
    return 6 + 68 + 2 + [self itemWidth] * [self numberOfRows] + 16;
}

- (void)setupSubviews
{
    self.selectionStyle = UITableViewCellSelectionStyleDefault;
    _picList = [NSMutableArray array];
    
    _textView = [[IJTextView alloc] init];
    @weakify(self);
    _textView.textChangedBlock = ^{
        @strongify(self);
        if (self.textChangedBlock) {
            self.textChangedBlock();
        }
    };
    _textView.placeholder = @"描述一下你的宝贝，不超过200字。";
    [self.contentView addSubview:_textView];
    [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(6);
        make.leading.mas_equalTo(10);
        make.trailing.mas_equalTo(-10);
        make.height.mas_equalTo(68);
    }];
    
    JCCollectionViewGridLayout *layout = [[JCCollectionViewGridLayout alloc] init];
    layout.minimumLeftSpacing = 16.f;
    layout.minimumRightSpacing = 10.f;
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    CGFloat width = [self itemWidth];
    layout.itemSize = CGSizeMake(width, width);
    _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView registerClass:[IJIssuePicCell class] forCellWithReuseIdentifier:NSStringFromClass([IJIssuePicCell class])];
    [_collectionView registerClass:[IJIssueAddPicCell class] forCellWithReuseIdentifier:NSStringFromClass([IJIssueAddPicCell class])];
    [self.contentView addSubview:_collectionView];
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(0);
        make.top.mas_equalTo(_textView.mas_bottom).mas_offset(2);
        make.bottom.mas_equalTo(-16);
    }];
}

- (CGFloat)itemWidth
{
    return (mScreenWidth - 16 - 10) / 4;
}

- (NSInteger)numberOfRows
{
    NSInteger count = self.picList.count + 1;
    if (count % 4 == 0) {
        return count / 4;
    }
    return count / 4 + 1;
}

- (IJImagesPicker *)imagesPicker
{
    if (!_imagesPicker) {
        _imagesPicker = [IJImagesPicker new];
    }
    return _imagesPicker;
}

- (void)reloadData
{
    if (self.reloadDataBlock) {
        self.reloadDataBlock();
    }
    [self.collectionView reloadData];
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.picList.count + 1;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == self.picList.count) {
        IJIssueAddPicCell *addPicCell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([IJIssueAddPicCell class]) forIndexPath:indexPath];
        return addPicCell;
    }
    IJIssuePicCell *picCell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([IJIssuePicCell class]) forIndexPath:indexPath];
    picCell.pic = self.picList[indexPath.row];
    @weakify(self);
    picCell.deleteBlock = ^(UIImage *pic) {
        @strongify(self);
        [self.picList removeObject:pic];
        [self reloadData];
    };
    return picCell;
}

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (![SystemHelper checkAndShowLoginViewControllerIfNotLogin]) {
        return;
    }
    if (indexPath.row == self.picList.count) {
        if (self.picList.count >= kIJMaxImagesCount) {
            [self ks_showToast:[NSString stringWithFormat:@"你最多只能选择%@张照片", @(kIJMaxImagesCount)]];
            return;
        }
        NSInteger lastCount = kIJMaxImagesCount - self.picList.count;
        @weakify(self);
        [self.imagesPicker pickerImagesWithMaxImagesCount:lastCount completion:^(NSArray<UIImage *> * _Nullable images) {
            @strongify(self);
            [self.picList addObjectsFromArray:images];
            
            
            NSMutableArray *imageDatas =@[].mutableCopy;
            [images enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSData *imageData = UIImageJPEGRepresentation(obj, 0.5);;
                [imageDatas addObject:imageData];
            }];
            //上传多张图片
            NSString *device = @"1";
            NSString *curtime = [PublicTool getNowTimeStamp];
            NSString *os_version = [SystemHelper osVersion];
            NSString *version = [SystemHelper appVersion];
            //拼接sign
            NSString *user_id = [TKAccountManager sharedManager].accountInfo.result.info.user_id;
            NSString *sign = [BLApi configSign:user_id andCurtime:curtime];
            NSDictionary *params = @{@"device":device,@"curtime":curtime,@"os_version":os_version,@"version":version,@"user_id":user_id,@"sign":sign,@"type":@"0"};
            [self ks_showProgress];
            @weakify(self);
            self.picUrlArray = @[].mutableCopy;
            [imageDatas enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [BLApi PostImageToUrl:URL_Image_uploading image:obj Params:params didFinish:^(id json, NSError *error) {
                    @strongify(self);
                    [self ks_hideProgress];
                    if (error) {
                        [self ks_showToast:error.domain];
                    } else {
                        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
                        NSDictionary *dcit = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
                        NSString *succeed = dcit[@"errmsg"];
                        if ([succeed isEqualToString:@"ok"]) {
                            NSDictionary *result = dcit[@"result"];
                            NSDictionary *info = result[@"info"];
                            NSString *url = info[@"url"];
                            [self ks_showToast:@"图片上传成功"];
                            //拿到url并赋值
                            [self.picUrlArray addObject:url];
                            [self reloadData];
                        } else {
                            [self ks_showToast:@"图片上传失败，请重试~"];
                            
                        }
                    }
                }];
 
            }];

        }];
    }
}

@end
